package com.enzoism.springboot.dive.scene2;

import com.enzoism.springboot.dive.common.AppConstants;
import com.enzoism.springboot.dive.common.CompareSortUtil;
import lombok.Data;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Map;

/**
 * 场景二：多字段排序（固定使用前端传递的字段顺序进行排序）
 * 默认按照usrId进行升序排列
 */
@Data
public class Scene2Model implements Serializable, Comparable<Scene2Model> {
    private static ThreadLocal<Map<String, String>> sortMap;
    private String usrId;
    private Long clkNum;
    private Long usrNum;

    public static ThreadLocal<Map<String, String>> getSortMap() {
        return sortMap;
    }

    public static void setSortMap(ThreadLocal<Map<String, String>> sortMap) {
        Scene2Model.sortMap = sortMap;
    }

    public static void unload() {
        if (null != sortMap) {
            sortMap.remove();
        }
    }

    @Override
    public int compareTo(Scene2Model model) {
        Map<String, String> sortMap = Scene2Model.getSortMap().get();
        if (MapUtils.isNotEmpty(sortMap)) {
            String clkNumSort = sortMap.get(AppConstants.ORDER_CLK_NUM);
            String usrNumSort = sortMap.get(AppConstants.ORDER_USR_NUM);
            String usrIdSort = sortMap.get(AppConstants.ORDER_USR_ID);
            if (this.getClkNum() != model.getClkNum()) {
                return CompareSortUtil.getSortIntValue(clkNumSort) * this.getClkNum().compareTo(model.getClkNum());
            } else if (this.getUsrNum() != model.getUsrNum()) {
                return CompareSortUtil.getSortIntValue(usrNumSort) * this.getUsrNum().compareTo(model.getUsrNum());
            } else if (this.getUsrId() != model.getUsrId()) {
                return CompareSortUtil.getSortIntValue(usrIdSort) * this.getUsrId().compareTo(model.getUsrId());
            }
        }
        return this.getUsrId().compareTo(model.getUsrId());
    }

    public Scene2Model(String usrId, long clkNum, long usrNum) {
        this.usrId = usrId;
        this.clkNum = clkNum;
        this.usrNum = usrNum;
    }
}
